/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package medicalassistant;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
/**
 *
 * @author Thomas
 */
public class LoginWindow extends javax.swing.JFrame {

    /**
     * Creates new form LoginWindow
     */
    public LoginWindow() {
        initComponents();
        // CALL SQL SERVER
        try {
            Class.forName("org.sqlite.JDBC");
            conn = DriverManager.getConnection("jdbc:sqlite:src/medicalassistant/medicalassistant.db");
            stat = conn.createStatement();
            System.out.println("SQLite connection successful!");
        } catch(ClassNotFoundException ex) {System.out.println(ex.getMessage());}
        catch(SQLException ex) {System.out.println(ex.getMessage());}
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        medAssistTitle = new javax.swing.JLabel();
        hospitalName = new javax.swing.JLabel();
        loginCard = new javax.swing.JPanel();
        loginBox = new javax.swing.JPanel();
        loginBoxFields = new javax.swing.JPanel();
        userLabel = new javax.swing.JLabel();
        username = new javax.swing.JTextField();
        passLabel = new javax.swing.JLabel();
        password = new javax.swing.JPasswordField();
        errorMessage = new javax.swing.JLabel();
        loginBoxButtons = new javax.swing.JPanel();
        loginButton = new javax.swing.JButton();
        forgotButton = new javax.swing.JButton();
        forgotBox = new javax.swing.JPanel();
        forgotBoxField = new javax.swing.JPanel();
        emailLabel = new javax.swing.JLabel();
        email = new javax.swing.JTextField();
        userRequestLabel = new javax.swing.JLabel();
        userRequest = new javax.swing.JTextField();
        ssidRequestLabel = new javax.swing.JLabel();
        ssidRequest = new javax.swing.JTextField();
        forgotBoxButtons = new javax.swing.JPanel();
        requestButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(450, 300));
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        medAssistTitle.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        medAssistTitle.setText("TeamFive Medical Assistant");
        getContentPane().add(medAssistTitle, new java.awt.GridBagConstraints());

        hospitalName.setText("Mercy Hospital");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        getContentPane().add(hospitalName, gridBagConstraints);

        loginCard.setPreferredSize(new java.awt.Dimension(350, 200));
        loginCard.setLayout(new java.awt.CardLayout());

        loginBox.setPreferredSize(new java.awt.Dimension(300, 150));
        loginBox.setLayout(new java.awt.GridBagLayout());

        loginBoxFields.setBorder(javax.swing.BorderFactory.createTitledBorder("Login"));

        userLabel.setText("Username:");

        username.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usernameActionPerformed(evt);
            }
        });

        passLabel.setText("Password:");

        errorMessage.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        errorMessage.setForeground(new java.awt.Color(255, 0, 0));
        errorMessage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        errorMessage.setText(" ");

        javax.swing.GroupLayout loginBoxFieldsLayout = new javax.swing.GroupLayout(loginBoxFields);
        loginBoxFields.setLayout(loginBoxFieldsLayout);
        loginBoxFieldsLayout.setHorizontalGroup(
            loginBoxFieldsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loginBoxFieldsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(loginBoxFieldsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(loginBoxFieldsLayout.createSequentialGroup()
                        .addGroup(loginBoxFieldsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(passLabel)
                            .addComponent(userLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(loginBoxFieldsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(username, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                            .addComponent(password))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(errorMessage, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        loginBoxFieldsLayout.setVerticalGroup(
            loginBoxFieldsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loginBoxFieldsLayout.createSequentialGroup()
                .addComponent(errorMessage)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginBoxFieldsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userLabel)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginBoxFieldsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passLabel)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        loginBox.add(loginBoxFields, new java.awt.GridBagConstraints());

        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });
        loginBoxButtons.add(loginButton);

        forgotButton.setText("Forgot Password");
        forgotButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                forgotButtonActionPerformed(evt);
            }
        });
        loginBoxButtons.add(forgotButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        loginBox.add(loginBoxButtons, gridBagConstraints);

        loginCard.add(loginBox, "Login");

        forgotBox.setPreferredSize(new java.awt.Dimension(350, 200));
        forgotBox.setLayout(new java.awt.GridBagLayout());

        forgotBoxField.setBorder(javax.swing.BorderFactory.createTitledBorder("Forgot Password"));

        emailLabel.setText("Email:");

        email.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                emailActionPerformed(evt);
            }
        });

        userRequestLabel.setText("Username:");

        userRequest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                userRequestActionPerformed(evt);
            }
        });

        ssidRequestLabel.setText("SSID:");

        ssidRequest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ssidRequestActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout forgotBoxFieldLayout = new javax.swing.GroupLayout(forgotBoxField);
        forgotBoxField.setLayout(forgotBoxFieldLayout);
        forgotBoxFieldLayout.setHorizontalGroup(
            forgotBoxFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(forgotBoxFieldLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(forgotBoxFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ssidRequestLabel)
                    .addComponent(userRequestLabel)
                    .addComponent(emailLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(forgotBoxFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(email, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                    .addComponent(userRequest)
                    .addComponent(ssidRequest))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        forgotBoxFieldLayout.setVerticalGroup(
            forgotBoxFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(forgotBoxFieldLayout.createSequentialGroup()
                .addGroup(forgotBoxFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userRequestLabel)
                    .addComponent(userRequest, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(forgotBoxFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(emailLabel)
                    .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(forgotBoxFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ssidRequestLabel)
                    .addComponent(ssidRequest, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        forgotBox.add(forgotBoxField, new java.awt.GridBagConstraints());

        requestButton.setText("Request Password");
        requestButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                requestButtonActionPerformed(evt);
            }
        });
        forgotBoxButtons.add(requestButton);

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        forgotBoxButtons.add(cancelButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        forgotBox.add(forgotBoxButtons, gridBagConstraints);

        loginCard.add(forgotBox, "Forgot Password");

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        getContentPane().add(loginCard, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void usernameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_usernameActionPerformed

    private void emailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_emailActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_emailActionPerformed

    private void forgotButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forgotButtonActionPerformed
        CardLayout cLayout = (CardLayout) (loginCard.getLayout());
        username.setText("");
        password.setText("");
        cLayout.show(loginCard, "Forgot Password");
    }//GEN-LAST:event_forgotButtonActionPerformed

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
        int ID = -1, userType = -1, doctorCount, patientCount, nurseCount;
        String pass = new String(password.getPassword());
        try {
            ResultSet set1 = stat.executeQuery("SELECT COUNT(*) FROM doctors WHERE username = '" + username.getText() + "' AND password = '" + pass + "';");
            doctorCount = set1.getInt(1);
            ResultSet set2 = stat.executeQuery("SELECT COUNT(*) FROM nurses WHERE username = '" + username.getText() + "' AND password = '" + pass + "';");
            nurseCount = set2.getInt(1);
            ResultSet set3 = stat.executeQuery("SELECT COUNT(*) FROM patients WHERE username = '" + username.getText() + "' AND password = '" + pass + "';");
            patientCount = set3.getInt(1);
            System.out.println(doctorCount + " " + nurseCount + " " + patientCount);
            if (doctorCount == 1) {
                ResultSet doctorID = stat.executeQuery("SELECT uid FROM doctors WHERE username = '" + username.getText() + "' AND password = '" + pass + "';");
                ID = doctorID.getInt("uid");
                userType = 2;
            }
            else if (nurseCount == 1) {
                ResultSet nurseID = stat.executeQuery("SELECT uid FROM nurses WHERE username = '" + username.getText() + "' AND password = '" + pass + "';");
                ID = nurseID.getInt("uid");
                userType = 1;
            }
            else if (patientCount == 1) {
                ResultSet patientID = stat.executeQuery("SELECT uid FROM patients WHERE username = '" + username.getText() + "' AND password = '" + pass + "';");
                ID = patientID.getInt("uid");
                userType = 0;
            }
        } catch (SQLException ex) {System.out.println(ex.getMessage());}
        catch (NullPointerException ex) {errorMessage.setText("ERROR: Please enter in a username and password."); System.out.println(ex.getMessage());}
        if (username.getText().equals("admin") && pass.equals("fishsticks")) {
            userType = 3;
        }
        if (userType > -1) {
            MedicalAssistantWindow mainProg = new MedicalAssistantWindow(ID, userType, conn);
            setVisible(false);
            mainProg.setVisible(true);
        }
        else errorMessage.setText("ERROR: Incorrect username/password combination.");
    }//GEN-LAST:event_loginButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        CardLayout cLayout = (CardLayout) (loginCard.getLayout());
        email.setText("");
        cLayout.show(loginCard, "Login");
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void requestButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_requestButtonActionPerformed
        int doctorCount = -1, nurseCount = -1, patientCount = -1;
        try {
            if((userRequest.getText().equals(""))||(email.getText().equals(""))||(ssidRequest.getText().equals("")))
            {
                JOptionPane.showMessageDialog(null, "Please fill all fields.", "Request Password", JOptionPane.ERROR_MESSAGE);
            }
            else
            {
                ResultSet set1 = stat.executeQuery("SELECT COUNT(*) FROM doctors WHERE username = '" + userRequest.getText() + "' AND ssn = '" + ssidRequest.getText() +  "' AND email = '" + email.getText() +"';");
                doctorCount = set1.getInt(1);
                    
                ResultSet set2 = stat.executeQuery("SELECT COUNT(*) FROM nurses WHERE username = '" + userRequest.getText() + "' AND ssn = '" + ssidRequest.getText() +  "' AND email = '" + email.getText() +"';");
                nurseCount = set2.getInt(1);
                    
                ResultSet set3 = stat.executeQuery("SELECT COUNT(*) FROM patients WHERE username = '" + userRequest.getText() + "' AND ssn = '" + ssidRequest.getText() +  "' AND email = '" + email.getText() +"';");
                patientCount = set3.getInt(1);

                System.out.println(doctorCount + " " + nurseCount + " " + patientCount);
                  
                if (doctorCount == 1)
                {
                    set1 = stat.executeQuery("SELECT password FROM doctors  WHERE username = '" + userRequest.getText() + "' AND ssn = '" + ssidRequest.getText() +  "' AND email = '" + email.getText() +"';");
                    JOptionPane.showMessageDialog(null, "You password is ["+set1.getString("password")+"].", "Request Password", JOptionPane.INFORMATION_MESSAGE);  
                }
                else if (nurseCount == 1)
                {
                    set2 = stat.executeQuery("SELECT password FROM nurses   WHERE username = '" + userRequest.getText() + "' AND ssn = '" + ssidRequest.getText() +  "' AND email = '" + email.getText() +"';");
                    JOptionPane.showMessageDialog(null, "You password is ["+set2.getString("password")+"].", "Request Password", JOptionPane.INFORMATION_MESSAGE);    
                }
                else  if (patientCount == 1)
                {
                    set3 = stat.executeQuery("SELECT password FROM patients WHERE username = '" + userRequest.getText() + "' AND ssn = '" + ssidRequest.getText() +  "' AND email = '" + email.getText() +"';");
                    JOptionPane.showMessageDialog(null, "You password is ["+set3.getString("password")+"].", "Request Password", JOptionPane.INFORMATION_MESSAGE); 
                }
                else 
                {
                    JOptionPane.showMessageDialog(null, "Incorrect information. Please try again.", "Request Password.", JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (SQLException ex) {System.out.println(ex.getMessage());} 
    }//GEN-LAST:event_requestButtonActionPerformed

    private void userRequestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userRequestActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_userRequestActionPerformed

    private void ssidRequestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ssidRequestActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_ssidRequestActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginWindow().setVisible(true);
            }
        });
    }
    // SQLite Variable declaration
    private Connection conn;
    private Statement stat;
    // End of SQLite Variable declaration
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField email;
    private javax.swing.JLabel emailLabel;
    private javax.swing.JLabel errorMessage;
    private javax.swing.JPanel forgotBox;
    private javax.swing.JPanel forgotBoxButtons;
    private javax.swing.JPanel forgotBoxField;
    private javax.swing.JButton forgotButton;
    private javax.swing.JLabel hospitalName;
    private javax.swing.JPanel loginBox;
    private javax.swing.JPanel loginBoxButtons;
    private javax.swing.JPanel loginBoxFields;
    private javax.swing.JButton loginButton;
    private javax.swing.JPanel loginCard;
    private javax.swing.JLabel medAssistTitle;
    private javax.swing.JLabel passLabel;
    private javax.swing.JPasswordField password;
    private javax.swing.JButton requestButton;
    private javax.swing.JTextField ssidRequest;
    private javax.swing.JLabel ssidRequestLabel;
    private javax.swing.JLabel userLabel;
    private javax.swing.JTextField userRequest;
    private javax.swing.JLabel userRequestLabel;
    private javax.swing.JTextField username;
    // End of variables declaration//GEN-END:variables
}
